package com.emperor.controller;


import com.emperor.dto.UserLoginDto;
import com.emperor.entity.User;
import com.emperor.properties.JwtProperties;
import com.emperor.result.Result;
import com.emperor.service.UserService;
import com.emperor.utils.AliOSSUtils;
import com.emperor.utils.JwtUtil;
import com.emperor.vo.UserIdVo;
import com.emperor.vo.UserLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private AliOSSUtils aliOSSUtils;

    @PostMapping("/login")
    public Result<UserLoginVo> login(@RequestBody UserLoginDto userLoginDto) {
        User login = userService.login(userLoginDto);
        System.out.println(login);
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", login.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        UserLoginVo userLoginVo = UserLoginVo.builder()
                .userId(login.getId())
                .username(login.getUserName())
                .roleCode(login.getRoleCode())
                .success(true).msg("登录成功")
                .regionId(String.valueOf(login.getRegionId())).isRepair(true)
                .token(token).build();
        return Result.success(userLoginVo);
    }

    @GetMapping("/{id}")
    public Result<UserIdVo> getUser(@PathVariable("id") Integer id) {
        UserIdVo user = userService.getUser(id);
        return Result.success(user);
    }

    @PostMapping("/fileUpload")
    public Result Upload(MultipartFile multipartFile) throws IOException {
        aliOSSUtils.upload(multipartFile);
        return Result.success();
    }
}
